$.fn.selectpicker.defaults = {noneSelectedText: "未选中任何项", noneResultsText: "没有找到匹配项", countSelectedText: "选中{1}中的{0}项", maxOptionsText: ["超出限制 (最多选择{n}项)", "组选择超出限制(最多选择{n}组)"], multipleSeparator: ", ", iconBase: 'fa', tickIcon: 'fa-check', liveSearch: true};
$.fn.ajaxSelectPicker.locale["zh-CN"] = {currentlySelected: "当前已选择", emptyTitle: "选择或查找...", errorText: "无法匹配到服务器数据", searchPlaceholder: "搜索...", statusInitialized: "输入开始查询", statusNoResults: "没有找到相关数据", statusSearching: "搜索中..."};
var uploaderlist = [];
var ajaxselect = {
    ajax: {
        url: null,
        data: function () {
            var params = {
                q: '{{{q}}}'
            };
            return params;
        }
    },
    localeCode: 'zh-CN',
    preprocessData: function (data) {
        var contacts = [];
        if (data.hasOwnProperty('Contacts')) {

        }
        return data;
    },
    preserveSelectedPosition: 'after',
    preserveSelected: true
};
var dom = {
    checkall: 'input[type="checkbox"].select-all',
    firsttd: 'tbody tr td:first-child',
    firstcheckbox: 'tbody tr td:first-child input[type="checkbox"]',
    toolbarbtn: '.toolbarinner .btn',
    dropdownbtn: 'thead tr th .dropdown-toggle',
    refreshbtn: '.toolbarinner button:first',
    loading: '<div><div class="animate text-center"><span class="fa fa-refresh fa-spin"></span> 加载中...</div></div>'
};
toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-center",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": "5000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
};
$.dialog = BootstrapDialog;
var dialogbuttons = [{
        id: 'submit-btn',
        label: '提交',
        cssClass: 'btn-primary',
        action: function (dialog) {
            var form = $("form", dialog.getModalBody());
            var beforeSubmit = form.data("before-submit");
            if (beforeSubmit && typeof window[beforeSubmit] == 'function') {
                var beforeSubmitCallback = window[beforeSubmit].call(form);
                if (!beforeSubmitCallback) {
                    return false;
                }
            }
            form.submit(function (e) {
                e.preventDefault();
                return false;
            });
            $('<input type="submit">').hide().appendTo(form).click().remove();
            if (form.get(0).checkValidity()) {
                var $button = this;
                $button.disable();
                $button.spin();
                $.ajax({
                    type: "POST",
                    url: form.prop("action"),
                    data: form.serialize(),
                    dataType: 'json',
                    success: function (data) {
                        if (data.hasOwnProperty("code")) {
                            var content = data.hasOwnProperty("content") && data.content != "" ? data.content : "";
                            if (data.code == 0) {
                                var afterSubmit = form.data("after-submit");
                                if (afterSubmit && typeof window[afterSubmit] == 'function') {
                                    var afterSubmitCallback = window[afterSubmit].call(form);
                                    if (!afterSubmitCallback) {
                                        return false;
                                    }
                                }
                                dialog.close();
                                $(dom.refreshbtn).trigger("click");
                                toastr.success(content ? content : "操作成功！");
                            } else {
                                toastr.error(content ? content : "操作失败！");
                            }
                        } else {
                            toastr.error("未知返回的数据格式,请重试！");
                        }
                    }, error: function () {
                        toastr.error("网络或服务器错误！");
                    }, complete: function (e) {
                        $button.enable();
                        $button.stopSpin();
                    }
                });
                //$("form", dialog.getModalBody()).submit();
                //dialog.setClosable(false);
            }
        }
    }, {
        id: 'cancel-btn',
        label: '关闭',
        cssClass: 'btn-default',
        action: function (dialog) {
            dialog.close();
        }
    }];
$(function () {
    $(window).on("load resize", function () {
        var height = $(".wrapper").height();
        //$(".menu").height(height);
        $(".page-wrapper").css("min-height", Math.max($(this).height(), $(".menu").height()));
    });
    $("#toggle-menu").on("click", function () {
        $(".menu").toggleClass("hidden-xs");
    });
    $(document).on("dblclick", "table.dataTable tbody tr td", function () {
        $("td a[data-action='edit']", $(this).parent()).trigger("click");
    });

    $(document).on("paste", ".pasteimg", function (event) {
        var that = this;
        // use event.originalEvent.clipboard for newer chrome versions
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        //console.log(JSON.stringify(items)); // will give you the mime types
        // find pasted image among pasted items
        var blob = null;
        for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") === 0) {
                blob = items[i].getAsFile();
            }
        }
        // load image if there is a pasted image
        if (blob !== null) {
            var reader = new FileReader();
            reader.onload = function (event) {
                fillimage(that, event.target.result);
            };
            reader.readAsDataURL(blob);
        }
    });

    $(document).on("dragover dragleave", ".pasteimg", function (event) {
        event.stopPropagation();
        event.preventDefault();
    });

    $(document).on("drop", ".pasteimg", function (event) {
        var that = this;
        event.stopPropagation();
        event.preventDefault();

        var files = event.originalEvent.target.files || event.originalEvent.dataTransfer.files;

        var reader = new FileReader();
        reader.onload = function (event) {
            fillimage(that, event.target.result);
        };
        reader.readAsDataURL(files[0]);
        return false;
    });
    var pagesize = 10;
    pagesize = Math.max(Math.floor(($(window).height() - 250) / 37), pagesize);
    $.extend(true, $.fn.dataTable.defaults, {
        "iDisplayLength": pagesize,
        "pagingType": "simple",
        'order': [1, 'desc'],
        'pageResize': true,
        "processing": true,
        "serverSide": true,
        "initComplete": function (settings, json) {
            initcomplete(settings);
        },
        "preDrawCallback": function (thead, data, start, end, display) {
            var wrapper = $(thead.nTableWrapper);
            var toolbardom = thead.oInit.custom.toolbardom != undefined ? thead.oInit.custom.toolbardom : '.toolbar';
            $(toolbardom).prependTo($(".toolbarinner", wrapper));
            $(".dataTables_filter input[type='search']", wrapper).attr("placeholder", "查找").css("width", "180");

        },
        "drawCallback": function (settings) {
            var wrapper = settings.nTableWrapper;
            $(dom.toolbarbtn + "[flip]", wrapper).attr("disabled", true);
            $(dom.checkall, wrapper).attr("checked", false);
        }
    });
    $(document).on("mouseenter", ".oldimg", function () {
        fillimage(this, $(this).prop("href"));
        return false;
    });
    //移除页面上的popover
    $('body').on('click', function (e) {
        $('[data-action="del"]').each(function () {
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });
});
function fillimage(obj, imgdata) {
    if (imgdata.length > 2048000)
        return toastr.error("图片大小不能超过2M");
    $(obj).val(imgdata);
    $(obj).popover({html: true, trigger: 'hover', content: function () {
            return '<img src="' + $(obj).val() + '" />';
        }}).popover('show');
}
//加载完成
function initcomplete(settings) {
    var wrapper = settings.nTableWrapper;
    var api = new $.fn.dataTable.Api(settings);
    //confirm event
    $(wrapper).on('click', '.popover-confirm-btn', function (e) {
        console.log($(this));
        e.stopPropagation();
        var popover = $(this).closest('.popover'),
                btn = popover.prev(),
                callback = btn.data('event');
        var fn = window[callback];
        if (typeof fn === 'function') {
            var ids = $(btn).data("ids") ? [$(btn).data("ids")] : selectedids(wrapper);
            fn.call(btn[0], "del", ids, wrapper, api);
        }
        btn.popover('hide');
    });
    //cancel event
    $(wrapper).on('click', '.popover-cancel-btn', function () {
        var popover = $(this).closest('.popover'),
                btn = popover.prev();

        btn.popover('hide');
    });
    $('.btn-filter ul li a', wrapper).on('click', function (e) {
        if ($(this).data("filter") == '') {
            $(this).parent().parent().find("li").removeClass("active");
            $(this).parent().parent().find("li:first").addClass("active");
        } else {
            $(this).parent().parent().find("li:first").removeClass("active");
            $(this).parent().toggleClass("active");
            if (0 == $(this).parent().parent().find("li.active").size()) {
                $(this).parent().parent().find("li:first").addClass("active");
            }
        }
        e.stopPropagation();
        api.ajax.reload();
    });
    //refresh event
    $(wrapper).on('click', dom.refreshbtn, function () {
        api.ajax.reload(null, false);
    });
    //check one event
    $(wrapper).on('click', dom.firsttd, function () {
        $("input[type='checkbox']", this).prop("checked", $(this).parent().hasClass("selected") ? false : true).change();
    });
    //check all event
    $(dom.checkall, wrapper).on('click', function (e) {
        $(dom.firstcheckbox, wrapper).prop('checked', this.checked).change();
        e.stopPropagation();
    });
    //check all(td) event
    $(dom.checkall, wrapper).parent().on('click', function (e) {
        $(dom.checkall, wrapper).trigger('click');
    });
    //checkbox event
    $(wrapper).on('click', dom.firstcheckbox, function (e) {
        //$(this).prop("checked", !$(this).prop("checked")).change();
        e.stopPropagation();
    }).on('change', dom.firstcheckbox, function () {
        if (this.checked) {
            $(this).closest("tr").addClass('selected');
        } else {
            $(this).closest("tr").removeClass('selected');
        }
        var selectedsize = $(dom.firstcheckbox + ':checked', wrapper).size();
        if (selectedsize > 0) {
            $(dom.toolbarbtn + ":disabled", wrapper).removeAttr("disabled").attr("flip", true);
            if (selectedsize === $(dom.firstcheckbox).size()) {
                $(dom.checkall, wrapper).prop("checked", true);
            }
        } else {
            $(dom.toolbarbtn + "[flip]", wrapper).attr("disabled", true);
            $(dom.checkall, wrapper).attr("checked", false);
        }

    });
    //dropdown event
    $(dom.dropdownbtn, wrapper).on("click", function (e) {
        $(this).parent().toggleClass("open");
        e.stopPropagation();
    });
    //toolbar btn event
    $(wrapper).on("click", "[data-event]", function () {
        var ids = $(this).data("ids");
        var placement = "bottom";
        if (ids !== undefined) {
            ids = [ids];
            placement = "left";
        } else {
            ids = selectedids(wrapper);
        }
        //console.log(ids);
        if (ids.length > 0) {
            var action = $(this).data("action");
            if (action == 'add') {
                opendialog(api.init().custom.add_url + "/ids/" + ids.join(","), "添加");
                return false;
            } else if (action == 'edit') {
                opendialog(api.init().custom.edit_url + "/ids/" + ids.join(","), "编辑");
                return false;
            } else if (action == 'fetch') {
                opendialog(api.init().custom.fetch_url + "/user_ids/" + ids.join(","), "<b>查看与ID为<font color='red'>" + ids[0] + "</font>的用户的聊天记录</b>");
                return false;
            } else if (action == 'move') {
                opendialog(api.init().custom.move_url + "/ids/" + ids.join(","), "移动");
            } else if (action == 'del') {
                $(".popover").popover("destroy");
                var buttons = "<span class='btn btn-primary popover-confirm-btn' data-ids='" + ids + "'>确定</span> <span class='btn btn-danger popover-cancel-btn' data-ids='" + ids + "'>取消</span>";
                $(this).popover({
                    title: "温馨提示",
                    html: true,
                    placement: placement,
                    trigger: 'click',
                    content: function () {
                        var selectedsize = ids.length;
                        return "<p><i class='fa fa-question-circle fa-3x'></i> 是否确认删除 " + selectedsize + " 条的数据?</p><span data-popover-confirm-container>" + buttons + "</span>";
                    }
                }).popover('show');
                $(this).on('hidden.bs.popover', function () {
                    $(this).popover("destroy");
                });
            } else {
                var fn = window[$(this).data("event")];
                if (typeof fn === 'function') {
                    fn.call(this, action, ids, wrapper, api);
                }
            }
        } else {
            toastr.error("请选择需要操作的数据");
        }
    });
}
function opendialog(url, title) {
    title = title == undefined ? "" : title;
    $.dialog.show({
        type: $.dialog.TYPE_DEFAULT,
        title: title,
        message: function (dialog) {
            var $message = $(dom.loading);
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad, function (ret) {
                //$("select", dialog.getModalBody()).select2({dropdownCssClass: 'dropdown-inverse'});
                $('.selectpicker', dialog.getModalBody()).selectpicker().filter("[data-abs-ajax-url]").ajaxSelectPicker(ajaxselect);

                dialog.setButtons(dialogbuttons);
            });
            return $message;
        },
        data: {
            'pageToLoad': url
        },
        width: '80',
        spinicon: 'fa fa-refresh',
        onshown: function (dialog) {
            $('.datetimepicker', dialog.getModalBody()).parent().css('position', 'relative');
            $('.datetimepicker', dialog.getModalBody()).datetimepicker({format: 'YYYY-MM-DD HH:mm:ss',
                icons: {
                    time: 'fa fa-clock-o',
                    date: 'fa fa-calendar',
                    up: 'fa fa-chevron-up',
                    down: 'fa fa-chevron-down',
                    previous: 'fa fa-chevron-left',
                    next: 'fa fa-chevron-right',
                    today: 'fa fa-history',
                    clear: 'fa fa-trash',
                    close: 'fa fa-remove'
                },
                showTodayButton: true,
                showClose: true});
            $(".summernote").summernote({
                height: 250,
                lang: 'zh-CN',
                dialogsInBody: true,
                onInit: function () {
                },
                onImageUpload: function (files, editor, $editable) {
                    sendFile(files[0], editor, $editable);
                }
            });
            //加载plupload
            initplupload(dialog);
        },
        onhidden: function (dialog) {
            $('.summernote').destroy();
        }
    });
}
function initplupload(dialog) {
    $(".plupload", dialog.getModalBody()).each(function () {
        var id = $(this).prop("id");
        uploaderlist[id] = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            multi_selection: false, //是否允许多选批量上传
            browse_button: id, // you can pass an id...
            container: $(this).parent().get(0), //取按钮的上级元素
            flash_swf_url: '/assets/mixins/plupload.swf',
            silverlight_xap_url: '/assets/mixins/plupload.xap',
            filters: {
                max_file_size: '20mb',
                mime_types: [
                    {title: "Image files", extensions: "jpg,gif,png"},
                    {title: "Zip files", extensions: "zip"},
                    {title: "Apk files", extensions: "apk"}
                ]
            },
            url: options.uploadurl,
            multipart_params: {
                'Filename': '${filename}', // adding this to keep consistency across the runtimes
                'Content-Type': '',
                'policy': options.policy,
                'signature': options.signature,
            },
            init: {
                PostInit: function () {

                },
                FilesAdded: function (up, files) {
                    plupload.each(files, function (file) {
                        //这里可以改成其它的表现形式
                        //document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
                    });
                    $("#" + id).data("bakup-html", $("#" + id).html());
                    //添加后立即上传
                    setTimeout(function () {
                        uploaderlist[id].start();
                    }, 1);
                },
                UploadProgress: function (up, file) {
                    //这里可以改成其它的表现形式
                    //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                    $("#" + id).prop("disabled", true);
                    $("#" + id).html("<i class='fa fa-upload'></i> 上传" + file.percent + "%");
                },
                FileUploaded: function (up, file, info) {
                    var response = JSON.parse(info.response);
                    //这里可以改成其它的表现形式
                    //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML += (' [Url]: ' + '<a href="' + url + '" target="_blank">' + url + '</a>');
                    //这里建议不修改
                    $("input[data-plupload-id='" + id + "-text']").val(response.url);
                    $("#" + id).prop("disabled", false).html($("#" + id).data("bakup-html"));
                    var afterUploaded = $("#" + id).data("after-uploaded");
                    if (afterUploaded && typeof window[afterUploaded] == 'function') {
                        window[afterUploaded].call(info, id, response);
                    }
                },
                Error: function (up, err) {
                    document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
                }
            }
        });

        uploaderlist[id].init();
    });
}

function sendFile(file, editor, welEditable) {
    var data = new FormData();
    data.append("file", file);
    $.ajax({
        url: "/king/ajax/upload",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            if (data.hasOwnProperty("code")) {
                var content = data.hasOwnProperty("content") && data.content != "" ? data.content : "";
                if (data.code == 0) {
                    $('.summernote').summernote("insertImage", data.content, 'filename');
                    toastr.success("上传成功！");
                } else {
                    toastr.error(content ? content : "操作失败！");
                }
            } else {
                toastr.error("未知返回的数据格式,请重试！");
            }
        }, error: function () {
            toastr.error("网络或服务器错误！");
        }
    });
}
//渲染完成,重新加载数据完成
function drawcomplete(dt) {
    $(window).trigger("resize");
    $(dom.firsttd, dt).drag("start", function (ev, dd) {
        return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
    }).drag(function (ev, dd) {
        $(dd.proxy).css({
            top: Math.min(ev.pageY, dd.startY),
            left: Math.min(ev.pageX, dd.startX),
            height: Math.abs(ev.pageY - dd.startY),
            width: Math.abs(ev.pageX - dd.startX)
        });
    }).drag("end", function (ev, dd) {
        $(dd.proxy).remove();
    });

    $(dom.firsttd, dt).drop("start", function () {
        toggleattr(this);
    }).drop(function () {
        toggleattr(this);
    }).drop("end", function () {
        toggleattr(this);
    });
    $.drop({
        multi: true
    });
}
function selectedids(wrapper) {
    var ids = $.map($('tr.selected', wrapper), function (tr) {
        return $(tr).attr("id");
    });
    return ids;
}
function toggleattr(wrapper) {
    $("input[type='checkbox']", wrapper).prop("checked", function (idx, oldprop) {
        return !oldprop;
    }).change();
}
var dtinit = function (dom) {
    var table = $(dom).on('draw.dt', function () {
        drawcomplete(this);
    }).on('preXhr.dt', function (e, settings, data) {
        var wrapper = settings.nTableWrapper;
        $(".toolbar button .fa-refresh", wrapper).addClass("fa-spin");
    }).on('xhr.dt', function (e, settings, json, xhr) {
        var wrapper = settings.nTableWrapper;
        $(".toolbar button .fa-refresh", wrapper).removeClass("fa-spin");
    });
    return table;
};
function dtmulti(action, ids, wrapper, api) {
    var url = action == "del" ? api.init().custom.del_url : api.init().custom.multi_url;
    $.ajax({
        type: "POST",
        url: url + "/ids/" + ids.join(","),
        data: {action: action, ids: ids, params: $(this).data("params")},
        dataType: 'json',
        success: function (data) {
            if (data.hasOwnProperty("code")) {
                var content = data.hasOwnProperty("content") && data.content != "" ? data.content : "";
                if (data.code == 0) {
                    $(dom.refreshbtn, wrapper).trigger("click");
                    toastr.success(content ? content : "操作成功！");
                } else {
                    toastr.error(content ? content : "操作失败！");
                }
            } else {
                toastr.error("未知返回的数据格式,请重试！");
            }
        }, error: function () {
            toastr.error("网络或服务器错误！");
        }
    });
    //console.log(action, ids);
}
function dtfilter(d) {
    $(dom.dropdownbtn + "[data-index]").each(function () {
        var index = parseInt($(this).data("index"));
        if ($("li.active a", $(this).next("ul"))) {
            d.columns[index].search.value = $.map($("li.active a", $(this).next("ul")), function (obj) {
                return $(obj).data("filter");
            }).join(",");
        }
    });
    return {"extra": 1000};
}

function beforesubmitform() {
    //console.log(this);
    return true;
}

function aftersubmitform() {
    //console.log(this);
    return true;
}

//检查配置
function checkconfig() {
    ret = false;
    try {
        $.parseJSON($("#content", this).val());
        ret = true;
    } catch (e) {
        toastr.error("内容格式错误:" + e);
        ret = false;
    }
    return ret;
}

//自定义上传完成回调
function afteruploaded(id, response) {
    toastr.success("自定义回调方法，当前测试提示，当前上传URL:" + response.url);
}